<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/22
 * Time: 14:34
 */

class Bank extends ADM_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->load->view('admin/money/bank/index.html');
    }

    public function info()
    {
        $send['state'] = false;
        do {

            if (empty($this->baseId)) {
                $send['error'] = '非法请求';
                break;
            }

            $q = $this->db->get('base_bank', ['baseId' => $this->baseId]);
            $row = $q->row_array();
            $data['data'] = [
                'bankname' => '',
                'kaihuhang' => '',
                'username' => '',
                'account' => ''
            ];
            if (!empty($row)) {
                $data['bankname'] = value($row, 'bankname');
                $data['username'] = value($row, 'username');
                $data['account'] = value($row, 'account');
                $data['kaihuhang'] = value($row, 'kaihuhang');
            }

            $send['state'] = true;
            $send['data'] = $data;

        } while(false);
        $this->output->send($send);
    }

    /**
     *
     */
    public function save()
    {
        $send['state'] = false;
        do {

            $params = $this->input->post();
            if (empty($params) || empty($params['bankname']) || empty($params['username']) ||
                empty($params['account']) || empty($params['kaihuhang'])) {
                $send['error'] = '参数错误';
                break;
            }

            if (!is_numeric($params['account'])) {
                $send['error'] = '银行卡号错误';
                break;
            }

            if (empty($this->baseId)) {
                $send['error'] = '非法请求';
                break;
            }

            $data = [
                'bankname' => value($params, 'bankname'),
                'kaihuhang' => value($params, 'kaihuhang'),
                'username' => value($params, 'username'),
                'account' => value($params, 'account')
            ];

            $exists = $this->getItemByBaseId($this->baseId);
            if (empty($exists)) {
                $data['baseId'] = $this->baseId;
                $this->db->insert('base_bank', $data);
                $res = $this->db->insert_id();
            } else {
                $this->db->update('base_bank', $data);
                $res = $this->db->affected_rows();
            }

            if ($res) {
                $send['state'] = true;
            } else {
                $send['error'] = '银行卡信息编辑失败';
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     * @param $baseId
     * @return mixed
     */
    private function getItemByBaseId($baseId)
    {
        $q = $this->db->get_where('base_bank', ['baseId' => $baseId]);
        return $q->row_array();
    }
}